<template>
    <van-nav-bar title="商品分类" left-text="返回" left-arrow @click-left="onClickLeft" />
    <!--类目分类-->
    <van-tree-select
      v-model:active-id="rightactiveId"
      v-model:main-active-index="leftactiveIndex"
      :items="categorydata"
    >
    <!--右侧图片信息-->
     <template #content>
       <van-grid :column-num="3" icon-size="50px">
      <van-grid-item v-for="item in categorydata[leftactiveIndex]?.children" 
      :key="item.id" 
      :icon="item.img" 
      :text="item.text" 
      :to="{name:'moveproductList',query:{id:item.id}}"/>
    </van-grid>

      </template>


    </van-tree-select>
    


</template>
<script setup lang="ts">

import { ref, onMounted } from 'vue';
import { CategoryApi } from '@/api';
//右侧选择项的id
const rightactiveId = ref(1)
// 左侧选择的索引值
const leftactiveIndex=ref(0)

const categorydata =ref([
    {
        text: '浙江',
        children: [
            { text: '杭州', id: 1,img:'https://m.360buyimg.com/babel/jfs/t1/114477/21/36707/8373/646da8d6Facec2806/fd8d1f9c0bb1bc5a.jpg' },
            { text: '温州', id: 2,img:'https://m.360buyimg.com/babel/jfs/t1/100342/15/41391/10528/646dad13F717b6cd9/a301d60c251994d8.jpg%22' },
            { text: '宁波', id: 3, disabled: true },
        ],
    },
])
const categoryData2 = ref([
    { id: 1, name: '手机数码', img: '', parentId: 0 },
    { id: 2, name: '华为手机', img: '', parentId: 1 },
    { id: 3, name: '三星手机', img: '', parentId: 1 },
    { id: 4, name: '家用电器', img: '', parentId: 0 },
    { id: 5, name: '电冰箱', img: '', parentId: 4 },
    { id: 6, name: '电饭煲', img: '', parentId: 4 },
         
    
])

onMounted(() => { 
    categoryData2.value.forEach((item:any) => { 
        item.text = item.name
    })
    // console.log(categoryData2);
   
    CallcategoryApi()
})

const CallcategoryApi = () => { 
    CategoryApi.select.call().then((res: any) => { 
       
        res.forEach((item: any) => {
            item.text = item.name
        })
         //使用高阶函数 reduce
        let categoryData3 = res.reduce((newArray: any, currentValue: any) => {
            currentValue.children = res.filter(
                (item:any) => {
                    return item.parentId === currentValue.id
                })
            if (currentValue.parentId === 0) {
                newArray.push(currentValue)
            }
            return newArray;
        }, [])
        categorydata.value = categoryData3
    })
}



const onClickLeft = () => history.back();
</script>
<style scoped></style>